package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.UserboundPaymentOrder;
import com.paypalpay.external.entity.querydevice.request.RequestDevice;
import com.paypalpay.external.entity.querydevice.response.Data;
import com.paypalpay.external.entity.querydevice.response.ResponseDevice;
import com.paypalpay.external.entity.querydevice.response.TradeData;
import com.paypalpay.external.entity.userbound.response.UtilsInterfaces;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.service.SequenceService;
import com.paypalpay.service.UserboundPaymentOrderService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询当前微信用户所持设备号的接口,用于前端返显，仅限微信访问
 *
 * @author lm
 * @date 2018/9/8
 */
@RestController
@Api(value = "查询当前微信用户所持设备号的接口")
public class QueryDeviceIdController {
    @Autowired
    HttpSession session;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    UserboundPaymentOrderService userboundPaymentOrderService;

    private String token = "yv8JXeTTfqyedLcU2LAqHUTKtYA4G1kz";
    private String tradeType = "F0005";

    @CrossOrigin
    @RequestMapping(value = "/getDeviceId", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String queryDeviceIdByOpenId(@RequestBody String requestStr) {

        System.out.println("请求报文是：" + requestStr);
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        String curtime = df.format(new Date());

        RequestDevice getDevice = JSONArray.parseObject(requestStr, RequestDevice.class);

        String requestSign = getDevice.getSign();
        if (getDevice.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            System.out.println("请求的sign是：" + requestSign);
            com.paypalpay.external.entity.querydevice.request.Data requestData = getDevice.getData();
            if (getDevice.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String partnerCode = requestData.getPartnerCode();
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String tradeTime = requestData.getTradeTime();
                String tradeType = requestData.getTradeType();
                if (getDevice.getData().getTradeData() == null) {
                    System.out.println("请求报文不合法:TradeData为空");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    // 将请求体json转成String
                    String str = JSON.toJSONString(requestData);
                    // 将Str拿去计算签名
                    String sign = utils.calculateSignature(str);
                    System.out.println("计算的sign是：" + sign);
                    // 验证签名
                    if (!requestSign.equalsIgnoreCase(sign)) {
                        // 签名不通过
                        String jsonString = utils.publicMessage(connSeqNo, tradeTime, partnerCode, token, tradeType);
                        return jsonString;
                    } else {
                        // 从请求json中取出请求openid
                        String openId = requestData.getTradeData().getOpenid();
                        // 1,从IccidUser数据库把数据取出来
                        if (openId.equals("") || openId == null) {
                            //openid为空，要返回"仅微信用户查询"
                            String jsonString = utils.openIdIsNull(connSeqNo, tradeTime, partnerCode, token, tradeType);
                            return jsonString;
                        } else {
                            String deviceId = "";
                            String deviceType = "";

                            List<UserboundPaymentOrder> deviceList = userboundPaymentOrderService.getDeviceByOpenId(openId);

                            List<TradeData> tradeData = new ArrayList<TradeData>();
                            TradeData trade = null;

                            //将数据库取回来的list
                            if (deviceList == null || deviceList.size() <= 0) {
                                // 2,可以开始拼接数据
                                Data data = new Data();
                                data.setConnSeqNo(connSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeData(tradeData);

                                ResponseDevice responseDeviced = new ResponseDevice();
                                responseDeviced.setData(data);
                                responseDeviced.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                String jsonString = JSON.toJSONString(responseDeviced);
                                System.out.println("回复的报文是：" + jsonString);
                                return jsonString;

                            } else {
                                // 取到设备信息
                                for (UserboundPaymentOrder user : deviceList) {
                                    //将拿到的数据拼接一下
                                    deviceId = user.getDeviceId();
                                    deviceType = user.getDeviceType();
                                    trade = new TradeData();
                                    trade.setDeviceId(deviceId);
                                    if (deviceType == null) {
                                        trade.setDeviceType("");
                                    } else {
                                        trade.setDeviceType(deviceType);
                                    }
                                    tradeData.add(trade);

                                }
                                Data data = new Data();
                                data.setConnSeqNo(connSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeData(tradeData);

                                ResponseDevice responseDeviced = new ResponseDevice();
                                responseDeviced.setData(data);
                                responseDeviced.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                String jsonString = JSON.toJSONString(responseDeviced);
                                System.out.println("回复的报文是：" + jsonString);
                                return jsonString;
                            }
                        }
                    }
                }
            }
        }
    }
}